<?php

/**
 * 小程序服务商管理系统 v1.0.1
 *
 * 商业运营到axzz.cn官网进行授权使用。
 *
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2025.03.22
 * Update at: 2025.11.22
 */

use App\Exceptions\JsonResponseException;
use App\Http\Middleware\AfterPassportResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Validation\ValidationException;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__.'/../routes/api.php',
        apiPrefix: '',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'permission' => Spatie\Permission\Middleware\PermissionMiddleware::class,
            'role' => Spatie\Permission\Middleware\RoleMiddleware::class,
            'role_or_permission' => Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
        ]);

        $middleware->append(AfterPassportResponse::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (Throwable $e)  {
            $env = config('app.env');

            match (true) {
                $e instanceof ValidationException => throw new JsonResponseException('The given data was invalid.', 422),
                $e instanceof AuthenticationException => throw new JsonResponseException('Unauthenticated. Please log in.', 401),
                $e instanceof UnauthorizedException => throw new JsonResponseException('You do not have the required authorization.', 403),
                $e instanceof MethodNotAllowedHttpException => throw new JsonResponseException('local' === $env ? $e->getMessage() : 'The requested resource was not found.', 404),
                $e instanceof NotFoundHttpException => throw new JsonResponseException('local' === $env ? $e->getMessage() : 'The requested resource was not found.', 404),
                $e instanceof InvalidArgumentException => throw new JsonResponseException('Invalid argument provided.', 400),
                default => throw new JsonResponseException('local' === $env ? $e->getMessage() : 'An unexpected error occurred.'),
            };
        });
    })->create();
